'use strict'

/**
 * <--    还原前    -->
for (var i=0; i<10086; i++)
  console.log(6666666);
console.log(7777777);

while (true)
  console.log(8888888);
 * 
 * <--    特点    -->
 * 语句块缺少大括号{}包围，观察得知，缺少BlockStatement节点，直接由第一条ExpressionStatement顶替
 * 即使添加上大括号，也只包围第一个语句，但是更易阅读
 * 
 * <--    解决办法    -->
 * 添加BlockStatement节点
 * 
 * <--    冗余判断    -->
 * 1. 支持语句块的语句
 * 2. 确实语句块
 * 
 * <--    还原后    -->
for (var i = 0; i < 10086; i++) {
  console.log(6666666);
}

console.log(7777777);

while (true) {
  console.log(8888888);
}
 *  
 **/

const {parse} = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const t = require('@babel/types');
const generator = require('@babel/generator').default;

let code = `for (var i=0; i<10086; i++)
console.log(6666666);
console.log(7777777);

while (true)
console.log(8888888);`

const visitor = {
    "ForStatement|ForOfStatement|ForInStatement|WhileStatement":{
        enter:function(path){
            let stmt = path.get('body');
            if(t.isBlockStatement(stmt)){return}
            stmt.replaceInline(t.blockStatement([stmt.node,]));
        },
    },
}

let ast = parse(code);
traverse(ast, visitor);
console.log(generator(ast).code);
